﻿#include <QJsonDocument>
#include "JZNetPack.h"

//JZNetPack
JZNetPack::JZNetPack()	
{		
    m_id = -1;
}

JZNetPack::~JZNetPack()
{
}

int JZNetPack::id() const
{
	return m_id;
}

void JZNetPack::setId(int seq)
{
	m_id = seq;
}

//JZNetPackJson
JZNetPackJson::JZNetPackJson()
{

}

JZNetPackJson::~JZNetPackJson()
{

}
		
int JZNetPackJson::type() const
{
	return NetPack_json;
}

void JZNetPackJson::saveToStream(QDataStream &s) const
{
    QJsonDocument doc(object);
	s << doc.toJson();
}

void JZNetPackJson::loadFromStream(QDataStream &s)
{
    QByteArray buffer;
	s >> buffer;

    QJsonDocument doc = QJsonDocument::fromJson(buffer);
    object = doc.object();
}

//JZNetPackManager
JZNetPackManager *JZNetPackManager::instance()
{
	static JZNetPackManager inst;
	return &inst;
}

JZNetPackManager::JZNetPackManager()
{	
}

JZNetPack *JZNetPackManager::createPack(int id)
{
	if (m_packFactory.contains(id))
		return m_packFactory[id]();
	
	return nullptr;
}

void JZNetPackManager::init()
{
    registPack(NetPack_json, JZNetPackCreate<JZNetPackJson>);
}

void JZNetPackManager::registPack(int type,CreatePackFunc func)
{
	Q_ASSERT(!m_packFactory.contains(type));
	m_packFactory.insert(type,func);
}

void JZNetPackInit()
{
	JZNetPackManager::instance()->init();
}